// import axios from "axios";
import { LgxCompressTool } from "../../canvas/common/tools/commpresstool";
import { KeyGenerator } from "../../canvas/common/keygenerator";
import { ElMessageBox } from 'element-plus'
var FileAccessSvc = {}

FileAccessSvc.open = function (fileUUID) {
    var url = "api/graph/getfiledata";
    var postBody = { "uuid": fileUUID };
    this.post2OpenFile(url, postBody);
}

FileAccessSvc.post2OpenFile = function (url, obj) {
    let that = this;
    axios.post(url, obj).then(res => {
        let respData = res.data;
        let graphFileDataStr = respData.data;
        let graphFileDataJsonObj = null;
        try {
            let deCompresData = LgxCompressTool.deCompresseBase64Str(graphFileDataStr);
            graphFileDataJsonObj= JSON.parse(deCompresData);
        }
        catch (error) {
            //原始未压缩的数据
            graphFileDataJsonObj= JSON.parse(graphFileDataStr);
        }
        finally {
            window.mainctl.initGraphObjFromStream(graphFileDataJsonObj, true);
            let fileInfo = respData.info;
            let uuid = fileInfo["uuid"];
            let name = fileInfo["name"];
            let parent = fileInfo["parent"];
            let iconURL = fileInfo["iconURL"];
            let maintype = fileInfo["maintype"];
            let projectid = fileInfo["projectid"];
            let userid = fileInfo["userid"];
            let fileMode = fileInfo["filetype"];
            let item = { uuid, name, parent, iconURL, projectid, userid, fileMode };
            window.gstore.commit("switchFile", item);
        }
    }).catch(function (error) {
        console.log(error);
    })
}

FileAccessSvc.openLGXFile = function(mainctl,base64String){
    let str = atob(base64String);
    let deCodeStr = LgxCompressTool.deCompresseBase64Str(str);
    let graphFileDataJsonObj = JSON.parse(deCodeStr);
    console.log(deCodeStr);
    mainctl.initGraphObjFromStream(graphFileDataJsonObj, true);
  }

  FileAccessSvc.post2UpdateFileData = function (mainctl,fileUUID) {
    var result = mainctl.m_pDataSavaINTF.save();
    var url = "api/graph/updateFileData";

    var postObj = {};
    postObj["uuid"] = fileUUID;
    let dataStr = JSON.stringify(result.data);
    let origLenth = dataStr.length;
    let compressData = LgxCompressTool.compresse2Base64Str(dataStr);
    let cpresLen = compressData.length;
    postObj["data"] = compressData;
    postObj["iconURL"] = LgxCompressTool.compresse2Base64Str(result.iconURL);
    let extInfoStr = JSON.stringify(result.extInfo);
    postObj["extInfo"] = extInfoStr;
  
    axios.post(url, postObj).then(res => {
      console.log(res.data);
    }).catch(function (error) {
      console.log(error);
    })
  }
  
  
  FileAccessSvc.post2SaveNewFile = function (mainctl,userid,fileName) {
    var result = mainctl.m_pDataSavaINTF.save();
    var url = "api/graph/save";
    var postObj = {};
    postObj["uuid"] = KeyGenerator.rid();
    postObj["data"] = LgxCompressTool.compresse2Base64Str(JSON.stringify(result.data));
    postObj["name"] = fileName;
    postObj["iconURL"] = result.iconURL;
    postObj["userid"] = userid;
    postObj["parent"] = "root";
    postObj["maintype"] = "file";
    postObj["filetype"] = result.data.fileMode;
    postObj["folder"] = "root";
    postObj["projectid"] = "";
  
    let extInfoStr = JSON.stringify(result.extInfo);
    postObj["extInfo"] = extInfoStr;
  
    axios.post(url, postObj).then(res => {
      let respData = res.data;
      console.log(res.data);
      let fileInfo = { uuid: postObj["uuid"], name: fileName, parent: "root", projectid: "", fileMode: result.data.fileMode };
      window.gstore.commit("switchFile", fileInfo);
  
    }).catch(function (error) {
      console.log(error);
    })
  }


  FileAccessSvc.saveFile = function () {
    console.log("save file");
    let userid = window.gstore.state.uid;
    if (!userid) {
      ElMessageBox.confirm('保存请先登录', 'Warning',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          let t = window.refLoginDlg.value;
          if (t && !t.visible) {
            t.visible = true;
          }
        })
        .catch(() => {
          return;
        })
  
      return;
    }
    let curenfileID = window.gstore.state.curentFile.uuid;
    if (curenfileID.length > 0) {
      FileAccessSvc.post2UpdateFileData(window.mainctl, curenfileID);
    }
    else {
      let fileName = "未命名";
      ElMessageBox.prompt('请输入文件名', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType: 'text',
          inputPattern: /\S/,
          inputErrorMessage: '文件名不能为空'
        }).then(({ value }) => {
          fileName = value;
          console.log('输入的内容为: ', value);
          FileAccessSvc.post2SaveNewFile(window.mainctl,window.gstore.state.uid,fileName);
        }).catch(() => {
          console.log('取消输入');
          return ;
        });
        
      
    }
  }
  
  FileAccessSvc.saveToLocal = function() {
    var result = window.mainctl.m_pDataSavaINTF.save();
    let fileName = window.gstore.state.curentFile.name + ".lgx";
  
    const data = LgxCompressTool.compresse2Base64Str(JSON.stringify(result.data));
    // const uint8Array = new TextEncoder().encode(data);
    // const blob = new Blob([uint8Array], { type: 'application/octet-stream' });
    const blob = new Blob([data], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
  
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
  
    document.body.appendChild(a);
    a.click();
  
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  }


export { FileAccessSvc }